import type { ActionRefType } from "@alipay/techui-rule-tree";
import { RuleTree } from "@alipay/techui-rule-tree";
import { Button, Form, Select, Space } from "antd";
import React, { useRef, useState } from "react";
import styled from "styled-components";
import { DeleteSvg } from "../../utils/constant";

const WrapperRuleTree = styled(RuleTree)`
  .rule-tree-item-drag {
    background-color: transparent;
    align-items: stretch;
  }
  .rule-tree-item-drag-holder {
    align-items: flex-start;
    margin-top: 4px;
  }
  .rule-tree-item {
    background-color: #f9f8fa;
    border-radius: 6px;
  }
  .rule-tree-node {
    display: block;
  }
  & > .rule-tree-node > div > .rule-tree-list > .rule-tree-item {
    margin-bottom: 16px;
    padding: 16px;
  }
` as typeof RuleTree;

export default function App() {
  const [value, setValue] = useState<any>({
    relation: "and",
    children: [
      {
        relation: "or",
        children: [{ name: "" }, { name: "" }, { name: "" }],
      },
      {
        relation: "or",
        children: [{ name: "" }, { name: "" }, { name: "" }],
      },
    ],
  });
  const actionRef = useRef<ActionRefType<{ name: string; age: number }>>(null!);
  return (
    <div>
      <p>
        虽然RuleTree的基本形态是固定的，但是仍然可以通过配置加覆盖样式达到一些定制化的效果
      </p>
      <WrapperRuleTree<{ name: string; age: number }>
        actionRef={actionRef}
        lineColor="transparent"
        createRender={(_, action, fields) => [
          <Button
            type="primary"
            key="add"
            onClick={() =>
              fields.levelPath.length !== 0 ? action.add() : action.addGroup()
            }
          >
            + 新增
          </Button>,
        ]}
        relationRender={(dom) => {
          return React.cloneElement(dom, {
            variant: "borderless",
            style: {
              background: "#f8f7f9",
            },
          });
        }}
        value={value}
        onChange={(value) => setValue(value)}
        nodeRender={({ listDom, relationDom }, fields) => {
          return (
            <>
              {fields.levelPath.length !== 0 && (
                <div
                  style={{ display: "flex", justifyContent: "space-between" }}
                >
                  <span style={{ fontWeight: "bold" }}>
                    {fields.index === 0 ? "如果" : "否则如果"}
                  </span>
                  {fields.index !== 0 && (
                    <Button
                      size="small"
                      type="text"
                      icon={DeleteSvg}
                      onClick={() => {
                        actionRef.current!.remove(
                          fields.levelPath.slice(0, -1),
                          fields.index
                        );
                      }}
                    />
                  )}
                </div>
              )}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                }}
              >
                {relationDom}
                {listDom}
              </div>
            </>
          );
        }}
        draggable={({ levelPath }) => {
          return !levelPath.length;
        }}
        relationFormItemRender={(dom, fields) => {
          const groupData = actionRef.current?.getGroupData(fields.levelPath);
          if (groupData?.children?.length === 1 || fields.deepth === 0) {
            return <div />;
          }
          return (
            <div style={{ position: "relative" }}>
              <div
                style={{
                  position: "absolute",
                  width: 40,
                  height: 66,
                  borderRadius: "6px 6px 6px 6px/ 6px 0px 0px 6px",
                  marginRight: 8,
                  top: -18,
                  left: 36,
                  border: "1px solid #9f9fa3",
                  borderRight: "none",
                }}
              />
              {dom}
            </div>
          );
        }}
        actionRender={({ removeDom }, _action, { index }) => {
          if (index === 0) {
            return [
              React.cloneElement(removeDom, {
                style: {
                  visibility: "hidden",
                },
                onClick: () => {},
              }),
            ];
          }
          return [removeDom];
        }}
      >
        {(field, index) => {
          const showTitle = index === 0;
          return (
            <>
              <Space>
                <Form.Item
                  style={{
                    marginBottom: 0,
                  }}
                  label={showTitle ? "参数名" : undefined}
                  name={[field.name, "name"]}
                  layout="vertical"
                  rules={[
                    { required: true },
                    {
                      validator(rule, value) {
                        if (value?.length < 2) {
                          return Promise.reject("长度不应小于2");
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Select style={{ width: 150 }} />
                </Form.Item>
                <Form.Item
                  style={{
                    marginBottom: 0,
                  }}
                  label={showTitle ? "选择条件" : undefined}
                  name={[field.name, "name"]}
                  layout="vertical"
                  rules={[
                    { required: true },
                    {
                      validator(rule, value) {
                        if (value?.length < 2) {
                          return Promise.reject("长度不应小于2");
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Select style={{ width: 150 }} />
                </Form.Item>
                <Form.Item
                  style={{
                    marginBottom: 0,
                  }}
                  label={showTitle ? "比较值" : undefined}
                  name={[field.name, "name"]}
                  layout="vertical"
                  rules={[
                    { required: true },
                    {
                      validator(rule, value) {
                        if (value?.length < 2) {
                          return Promise.reject("长度不应小于2");
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Space.Compact>
                    <Select style={{ width: 100 }} />
                    <Select style={{ width: 100 }} />
                  </Space.Compact>
                </Form.Item>
              </Space>
            </>
          );
        }}
      </WrapperRuleTree>
      <pre>{JSON.stringify(value, null, 2)}</pre>
    </div>
  );
}
